#!/usr/bin/env python
# encoding: utf-8
"""
...
"""

#
#  Copyright (c) 2009 University of Dundee. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
#  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
#  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#  SUCH DAMAGE.

import unittest
import sys

from StringIO import StringIO
from getopt import getopt, GetoptError
from copy import deepcopy
from xsltbasic import XsltBasic
# We're using lxml's ElementTree implementation for XML manipulation due to
# its XSLT integration.
from lxml.etree import XML, XSLT, XMLSchema, XMLSchemaValidateError, Element, SubElement, ElementTree, dump, parse

# Handle Python 2.5 built-in ElementTree
#try:
#        from xml.etree.ElementTree import XML, Element, SubElement, ElementTree, dump
#except ImportError:
#        from elementtree.ElementTree import XML, Element, SubElement, ElementTree, dump


def usage(error):
    """Prints usage so that we don't have to. :)"""
    cmd = sys.argv[0]
    print """%s
Usage: %s <stylesheet.xsl> <input.xml> [output.xml]
Runs the stylesheet transform upon an XML instance document.

Options:

Examples:
  %s foo.xslt bar.xml bar_new.xml

Report bugs to ome-devel@lists.openmicroscopy.org.uk""" % (error, cmd, cmd)
    sys.exit(2)

def run_stylesheet(xslt, document):
    xslt_doc = parse(xslt)
    transform = XSLT(xslt_doc)
    return transform(document)


class Test200802(XsltBasic):

    STYLESHEET = "../specification/Xslt/2007-06-to-2008-09.xsl"

    OLD_VALIDATION = "../specification/Released-Schema/2007-06/ome.xsd"
    NEW_VALIDATION = "../specification/Released-Schema/2008-09/ome.xsd"

    DOCUMENT = "../specification/InProgress/test-ome-samples/sample-2007-06.ome"

    OLD_OME_NS = "http://www.openmicroscopy.org/Schemas/OME/2007-06"

    OLD_SPW_NS = "http://www.openmicroscopy.org/Schemas/SPW/2007-06"

    NEW_OME_NS = "http://www.openmicroscopy.org/Schemas/OME/2008-09"

    NEW_SPW_NS = "http://www.openmicroscopy.org/Schemas/SPW/2008-09"

    def setUp(self):
        self.xslt_file = open(self.STYLESHEET)
        self.instance_file = open(self.DOCUMENT)
        self.instance_document = parse(self.instance_file)
        self.result = run_stylesheet(self.xslt_file, self.instance_document)
        self.old_root = self.instance_document.getroot()
        self.new_root = self.result.getroot()

    def tearDown(self):
        self.xslt_file.close()
        self.instance_file.close()

#    def test_dummy(self):
#        print self.result

    def test_validate_input(self):
        """
            Checks that the input validates
        """
        # load the old schema
        try:
            schema = XMLSchema(parse(self.OLD_VALIDATION))
        except:
            # chosen schema failed to laod
            print "Validator Internal error: XSD schema file could not be found [OLD]"

        # validating the document tree against the loaded schema
        # according to the docs this should not throw an exception - but it does!
        try:
            schema.validate(self.old_root)
            isXsdValid = True
            for err in schema.error_log:
                isXsdValid = False
                print "File: %s Line: (%s, %s) Type: %s (%s) - %s\n" % ("Input", err.line, None, "XSD", None, err.message)

        except XMLSchemaValidateError:
            isXsdValid = False
            print "File: %s Line: (%s, %s) Type: %s (%s) - %s\n" % ("Input", None, None, "XML", None, "Processing the XML data has generated an unspecified error in the XML sub-system. This is usually a result of an incorrect top level block. Please check the OME block is well-formed and that the schemaLocation is specified correctly. This may also be caused by a missing namespace prefix or incorrect xmlns attribute.")

        self.assertTrue(isXsdValid);


    def test_validate_output(self):
        """
            Checks that the output validates
        """
        # load the new schema
        try:
            schema = XMLSchema(parse(self.NEW_VALIDATION))
        except:
            # chosen schema failed to laod
            print "Validator Internal error: XSD schema file could not be found [NEW]"

        # validating the document tree against the loaded schema
        # according to the docs this should not throw an exception - but it does!
        try:
            schema.validate(self.new_root)
            isXsdValid = True
            for err in schema.error_log:
                isXsdValid = False
                print "File: %s Line: (%s, %s) Type: %s (%s) - %s\n" % ("Output", err.line, None, "XSD", None, err.message)

        except XMLSchemaValidateError:
            isXsdValid = False
            print "File: %s Line: (%s, %s) Type: %s (%s) - %s\n" % ("Output", None, None, "XML", None, "Processing the XML data has generated an unspecified error in the XML sub-system. This is usually a result of an incorrect top level block. Please check the OME block is well-formed and that the schemaLocation is specified correctly. This may also be caused by a missing namespace prefix or incorrect xmlns attribute.")
            print "File is invalid"

        self.assertTrue(isXsdValid);



if __name__ == '__main__':
    unittest.main()
"""
    try:
        options, args = getopt(sys.argv[1:], "")
    except GetoptError, (msg, opt):
        usage(msg)

    for option, argument in options:
        pass

    xslt_filename = "2008-09.xsl"
    xslt = open(xslt_filename)
    in_filename = "tmp/sample-lsm-nobindata.ome"
    in_file = open(in_filename)
    try:
        print "Running XSLT %s on %s..." % (xslt_filename, in_filename)
        run_stylesheet(xslt, in_file, None)
    finally:
        xslt.close()
        in_file.close()
"""
